<template>
  <div class="member-page">
    <div class="member-header">
      <h3 class="member-title">成员管理</h3>
      <el-button type="primary" @click="handleAdd" v-permission="'project:manage:member:create'">
        <IconAddMember class="mr-4px" />添加成员
      </el-button>
    </div>

    <div class="member-list">
      <query-list ref="queryBoxRef" :fetch-method="fetchMethod" :show-pagination="true" :default-page-size="10"
        @reset="handleReset">
        <!-- 查询条件插槽 -->
        <template #query>
          <el-form-item label="用户名">
            <el-input v-model="form.filter.username" placeholder="请输入用户名或邮箱" clearable />
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="form.filter.nickname" placeholder="请输入用户昵称" clearable />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="form.filter.role_id" clearable style="min-width: 200px">
              <el-option v-for="role in roleList" :label="role.name" :value="role.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="加入时间">
            <el-date-picker v-model="form.filter.joinTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 240px"
              @change="handleJoinTimeChange" />
          </el-form-item>
        </template>

        <!-- 数据展示插槽 -->
        <template #default="{ data, loading }">
          <el-table :data="data" v-loading="loading" style="width: 100%" stripe>
            <el-table-column prop="username" label="用户名" min-width="200">
              <template #default="{ row }">
                <div class="user-info">
                  <img src="@/assets/user.webp" class="user-avatar" alt="用户头像">
                  <span class="username">{{ row.username || '-' }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="name" label="用户昵称" min-width="150">
              <template #default="{ row }">
                {{ row.name || row.nickname || '-' }}
              </template>
            </el-table-column>

            <!-- <el-table-column prop="email" label="邮箱" min-width="240">
            <template #default="{ row }">
              zhangsan@example.com
            </template>
          </el-table-column> -->

            <el-table-column prop="role_name" label="角色" min-width="120">
              <template #default="{ row }">
                {{ row.role_name || '-' }}
              </template>
            </el-table-column>

            <el-table-column prop="joinTime" label="加入时间" min-width="140">
              <template #default="{ row }">
                {{ formatDayTime(row.join_time) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="150" fixed="right"
              v-if="userStore.hasPermission(['project:manage:member:edit', 'project:manage:member:delete'], 'project', true, userStore.currentProjectId)">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)"
                  v-permission="'project:manage:member:edit'" v-if="row.role_type !== 'admin'">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)"
                  v-permission="'project:manage:member:delete'" v-if="row.role_type !== 'admin'">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </query-list>
    </div>
  </div>
  <MemberDialog v-model="showMemberDialog" :id="userId" @changed="handleRefresh" />
  <el-dialog v-model="showAddMemberDialog" width="450" title="添加成员">
    <el-form>
      <el-form-item label="请输入用户名">
        <el-select v-model="userIdAdd" clearable style="min-width: 200px">
          <el-option v-for="user in userList" :label="user.username" :value="user.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleAddMember">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import QueryList from '@/common/components/QueryList.vue';
import { getProjectMemberList, getRoleListApi, deleteProjectMember, getUserList, addProjectMember } from '@/common/apis/projectMember/index.ts';
import { formatDayTime } from '@/common/utils/datetime.ts';
import { useRoute } from 'vue-router';
import MemberDialog from './MemberDialog.vue';
import { cloneDeep } from 'lodash-es';
import { useUserStore } from '@/store/modules/user';

const roleList = ref<any[]>([]);
const route = useRoute();
const userId = ref<number | null>(null);
const showMemberDialog = ref(false);
const queryBoxRef = ref();
const userStore = useUserStore();
const showAddMemberDialog = ref(false);
const userList = ref<any>([]);
const userIdAdd = ref();

// 查询表单数据
const defaultFormData = {
  filter: {
    username: '',
    nickname: '',
    role_id: '',
    joinTime: [], // 存储 YYYY-MM-DD 格式
    joinTimeStamp: [], // 存储时间戳字符串
  },
  orderBy: [
    {
      field: 'joinTime',
      strategy: 'DESC',
    },
  ],
};

const form = ref(cloneDeep(defaultFormData));

const handleJoinTimeChange = (dates: string[] | null) => {
  if (dates && dates.length === 2 && dates[0] && dates[1]) {
    // 转换日期字符串为10位时间戳字符串（秒级）
    form.value.filter.joinTimeStamp = [
      String(Math.floor(new Date(dates[0]).getTime() / 1000)),
      String(Math.floor(new Date(dates[1]).getTime() / 1000)),
    ];
  } else {
    // 清空两个数组
    form.value.filter.joinTime = [];
    form.value.filter.joinTimeStamp = [];
  }
};

const fetchMethod = async (_params: { pageNum: number; pageSize: number; }) => {
  const { pageNum, pageSize } = _params;
  const { filter, orderBy } = form.value;
  const { username, nickname, role_id, joinTimeStamp } = filter;

  try {
    const params = {
      projectId: userStore.currentProjectId,
      filter: {
        username,
        nickname,
        role_id,
        joinTimeStamp
      },
      pageNum,
      pageSize,
      orderBy,
    };

    const { data } = await getProjectMemberList(params);

    if (data) {
      return {
        data: data?.list || [],
        total: data?.total || 0,
      };
    } else {
      return {
        data: [],
        total: 0,
      };
    }
  } catch (e) {
    console.error(e);
    return {
      data: [],
      total: 0,
    };
  }
};

const handleClose = () => {
  showAddMemberDialog.value = false;
  userIdAdd.value = null;
};

const handleAdd = async () => {
  showAddMemberDialog.value = true;
  const { data } = await getUserList();
  userList.value = data;
};

const handleAddMember = async () => {
  const res = await addProjectMember({ userId: userIdAdd.value, projectId: userStore.currentProjectId });
  ElMessage.success({ message: `${res.message}` });
  handleRefresh();
  showAddMemberDialog.value = false;
  userIdAdd.value;
};

const handleRefresh = () => {
  queryBoxRef.value.refresh();
};

const handleEdit = (row: any) => {
  userId.value = row.user_id;
  showMemberDialog.value = true;
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${row.nickname}" 吗？此操作不可撤销`,
    'warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const res = await deleteProjectMember({ id: row.user_id, projectId: userStore.currentProjectId });
    ElMessage.success({ message: `${res.message}` });
    handleRefresh();
  }).catch(() => {
  });
};

// 重置功能
const handleReset = () => {
  // 重置表单数据到默认值
  form.value = cloneDeep(defaultFormData);

  // 刷新数据
  handleRefresh();
};

onMounted(async () => {
  const { data } = await getRoleListApi({ projectId: userStore.currentProjectId });
  roleList.value = data;
});

// 暴露给父组件用于刷新列表
defineExpose({
  queryBoxRef,
});
</script>

<style lang="less" scoped>
.member-page {
  background: var(--bg-primary);
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;

  .member-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .member-title {
      font-size: 20px;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0;
    }
  }

  .member-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    // 表格样式调整
    :deep(.el-table) {
      .el-table__header-wrapper {
        position: sticky;
        top: 0;
        z-index: 10;
        background: var(--bg-primary);
      }

      .el-table__body-wrapper {
        max-height: calc(100vh - 300px); // 根据实际需要调整高度
        overflow-y: auto;
      }
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .username {
      font-weight: 500;
      color: var(--text-primary);
    }
  }
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
</style>